import router from "@/router";
import { KeepAlive } from "vue";

// 菜单树转对象: name为key
function getMenuObj(menus, obj = {}) {
  menus.forEach(item => {
    if (item.path) {
      obj[item.path] = {
        name: item.name,
        buttons: item.buttons || []
      }
    }
    if (Array.isArray(item.children)) {
      return getMenuObj(item.children, obj)
    }
  })
  return obj
}

// 获取第一个菜单路径
function getFirstPath(menu) {
  let path = menu?.path || '/login'
  if (Array.isArray(menu.children)) {
    path = getFirstPath(menu.children[0], path)
  }
  return path
}

//动态导入路由，import.meta.glob() 为vite提供的方法
// let modules = import.meta.glob(`../../views/**/*.vue`)
// let modules2 = import.meta.glob(`../../components/**/*.vue`)
// const modules = import.meta.glob('@/view/pages/**/*.vue')

//获取view下所有的vue文件
const modules = import.meta.glob('../views/pages/*/*/*.vue'); //如果文件路径修改了则 需要修改这里  比如 sys/admin/index.vue;
const modules2 = import.meta.glob('../views/pages/*/*.vue'); //如果文件路径修改了则 需要修改这里  比如 admin/index.vue;
//菜单导入动态菜单
function formatRoute(arr) {
  for (let index = 0; index < arr.length; index++) {
    const e = arr[index];
    e.component ='';
    // console.log(e,"路由")
    if(e.path !=''){
      // console.log(e,"路由")
      var num = (arr[index].path.match(/\//g) || []).length;//判断路径是  sys/admin/index.vue 还是 admin/index.vue
      if (num == 3) {
        e.component = modules[`../views/pages${e.path}.vue`];
      } else {
        e.component = modules2[`../views/pages${e.path}.vue`];
      }
      // e.meta.keepAlive=true; //缓存
      // e.meta = {KeepAlive:true};
      // console.log(e,"路由");
    router.addRoute("layout",e);//加入动态路由 并添加在 "layout"路由下
    }
    if (e.children) {
      formatRoute(e.children)
    }
  }
  // console.log(arr,"456");
  return arr;
}


// 获取所有的菜单路径
function getMenuPath(menu) {
  
  const newArr =[];
  if(menu && menu.length > 0){

    for (let index = 0; index < menu.length; index++) {
      const e = menu[index];
      if(e.path !=''){
        newArr.push(e.path);
      }
      if (e.children) {
        e.children.map((key)=>{
          if(key.path !=''){
            newArr.push(key.path);
          }
        })
      }
    }

  }
  // console.log(menu,"5");
  return newArr;

}

export {
  getMenuObj,
  getFirstPath,
  formatRoute,
  getMenuPath
}